package com.korubo.web.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.korubo.kit.R;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.korubo.web.mapper.MenuMapper;
import com.korubo.web.model.Menu;
import com.korubo.web.service.MenuService;

@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Resource
    private MenuMapper mapper;

    @Override
    public R listTree(Menu menu) {
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        if (null != menu && StrUtil.isNotBlank(menu.getName())) {
            queryWrapper.like("name", menu.getName());
        }
        queryWrapper.orderByAsc("sort");
        List<Menu> menus = mapper.selectList(queryWrapper);
        List<Menu> tree = tree(menus);
        return R.ok(tree);
    }

    private List<Menu> tree(List<Menu> records) {
        //转成map
        Map<String, Menu> map = records.stream().collect(HashMap::new, (k, v) -> k.put(v.getId(), v), HashMap::putAll);
        List<Menu> menus = new ArrayList<>();
        for (Menu menu : records) {
            if (menu.getParentId() != null) {
                Menu parent = map.get(menu.getParentId());
                if (null == parent) {
                    menus.add(menu);
                    continue;
                }
                if (null == parent.getChildren()) {
                    parent.setChildren(new ArrayList<>());
                }
                parent.getChildren().add(menu);
            } else {
                menus.add(menu);
            }
        }
        return menus;
    }

}
